<?php
class LocationController extends BaseApiController
{

    function init()
    {
        parent::init();
    }


    #上传用户信息
    function putLocationAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口

        $longitude = sprintf("%.7f",$_REQUEST['longitude']);  //经度
        $latitude = sprintf("%.7f",$_REQUEST['latitude']);  //纬度
        $destination = trim($_REQUEST['destination']);  //位置名称

        if(empty($longitude) || empty($latitude) || empty($destination)){
            $code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        if($longitude > 180 || $latitude>90){ //经度,纬度的最大值分别是180度,90度。
            $code = 10007; //参数错误
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }


        #更新用户最新位置消息
        $new_location_model = new NewLocationModel();
        $location_info = $new_location_model->getDataByUid($uid);
        if(empty($location_info)){ //第一次就添加
            $insert = array(
                'uid' => $uid,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'destination' => $destination,
                'created_at' => time(),
                'updated_at' => time(),
            );
            $new_location_model->addData($insert);
        }else{ //修改

            $update = array(
                'longitude' => $longitude,
                'latitude' => $latitude,
                'destination' => $destination,
                'updated_at' => time(),
            );
            $new_location_model->updateDataByUid($update, $uid);
        }


        #存储用户位置
        $location_model = new LocationModel();
        $add_data = array(
            'uid' => $uid,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'destination' => $destination,
            'created_at' => time()
        );
        $ret = $location_model->addData($add_data);
        if(empty($ret)){
            $code = 10007; //参数错误
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }


    #获取用户轨迹
    function getTravelAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $start_time =  isset($_REQUEST['start_time']) ? strtotime(trim($_REQUEST['start_time'])) : ''; //轨迹开始时间
        $end_time =  isset($_REQUEST['end_time']) ? strtotime(trim($_REQUEST['end_time'])) : time(); //轨迹结束时间
        $friend_id =  isset($_REQUEST['friend_id']) ? intval($_REQUEST['friend_id']) : ''; //好友uid为空就是查看自己的轨迹

        if(empty($start_time)){
            $start_time = $end_time - 3600;
        }

        if($start_time < time() - 24 * 60 * 60 * 30){
            $code = 26009; //查询时间间隔最长30天，请修改
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        $space = $end_time - $start_time;
        if($space > 24 * 60 * 60){
            $code = 26001; //查询时间间隔最长24小时，请修改
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }


        if(empty($friend_id)){

            $location_model = new LocationModel();
            $condition = array(
                'start_time' => $start_time,
                'end_time' => $end_time,
                'uid' => $uid
            );
            $data = $location_model->getListByCondition($condition);
            if(empty($data)){
                $code = 26013; //当前时段未收录位置信息，请查看其他时段
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

        }else{
            $user_list_model = new UserListModel();
            $friendship = $user_list_model->getFriends($uid, $friend_id);
            if(empty($friendship)){
                $code = 26010; //你们还不是朋友
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            if($friendship['side_hide'] == 2){
                $code = 26011; //'该好友隐匿了自己，赶紧让他开启定位对你可见吧！',
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            $location_model = new LocationModel();
            $condition = array(
                'start_time' => $start_time,
                'end_time' => $end_time,
                'uid' => $friend_id
            );
            $data = $location_model->getListByCondition($condition);
            if(empty($data)){
                $code = 26012; //'该好友隐匿了自己，赶紧让他开启定位吧（在设置--在哪--位置--始终中开启）',
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE,$data);
    }

    #制定一个约会
    function makeDateAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $time = time();

        $longitude = sprintf("%.7f",$_REQUEST['longitude']);  //经度
        $latitude = sprintf("%.7f",$_REQUEST['latitude']);  //纬度
        $destination = trim($_REQUEST['destination']);  //位置名称
        $date_id = isset($_REQUEST['date_id']) ? $_REQUEST['date_id'] : '0';  //约会ID
        $begin_at = isset($_REQUEST['begin_at']) ? strtotime($_REQUEST['begin_at']) : '0';  //约会时间
        $uids = isset($_REQUEST['friend_ids']) ? explode(',', trim($_REQUEST['friend_ids'])) : array(); //参加的uid好友

        if(empty($uids)){
            $code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }


        $uids_k_v = array();
        foreach($uids as $uid_key){
            $uids_k_v[$uid_key] = $uid_key;
        }
        $uids = $uids_k_v;

        if($longitude > 180 || $latitude>90 || $longitude <= 0 || $latitude<=0){ //经度,纬度的最大值分别是180度,90度。
            $code = 10007; //参数错误
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        $appointment_model = new AppointmentModel();
        $notice_model = new NoticeModel();
        $user_list_model = new UserListModel();
        $date_records_model =  new DateRecordsModel();
        $user_model = new UserModel();

        if(empty($date_id)){ //新建约会
            #先检查是否有约会在进行中
            $on_date = $date_records_model->getDateByUid($uid);
            if($on_date){
                $code = 26006; //'您已经处于一个约会中，请退出当前约会后再试'
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            $user_info = $user_model->getUserInfoByUid($uid);
            if(empty($user_info)){
                $code = 20049; //用户不存在或已注销
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }else{
                if(empty($user_info['member'])){
                    $code = 26007; //不是会员，请充值
                    $msg = $this->_error_msg->system_errors[$code];
                    return $this->echo_message($msg,$code);
                }
            }

            $date_records_model->beginTransaction();
            $insert = array(
                'uid' => $uid,
                'status' => 1,
                'destination' => $destination,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'expired_at' => $time + 24*60*60, //24小时过期
                'created_at' => $time,
                'begin_at' => $begin_at,
            );
            $date_id = $date_records_model->addData($insert);

            if($date_id){
                $uids[] = $uid;
                foreach($uids as $val){ //先判断每一个人是不是都有约会
                    $on_date = $appointment_model->getDataByUid($val);//查询用户是否已经处于约会
                    if($on_date){
                        $date_records_model->rollback();
                        $code = 26006; //'您已经处于一个约会中，请退出当前约会后再试'
                        $msg = "用户".$this->_error_msg->system_errors[$code];
                        return $this->echo_message($msg,$code);
                    }
                }

                foreach($uids as $val){
                    $friend_info = $user_model->getUserInfoByUid($val); //查询用户信息
                    if(empty($friend_info)){
                        $date_records_model->rollback();
                        $code = 20049; //用户不存在或已注销
                        $msg = $this->_error_msg->system_errors[$code];
                        return $this->echo_message($msg,$code);
                    }

                    $appoint_info = array(
                        'date_id' => $date_id,
                        'uid' => $val,
                        'promoter' => $uid,
                        'destination' => $destination,
                        'longitude' => $longitude,
                        'latitude' => $latitude,
                        'expired_at' => $time + 24*60*60, //24小时过期
                        'created_at' => $time,
                        'begin_at' => $begin_at
                    );
                    $ret = $appointment_model->addData($appoint_info);
                    if(!$ret){
                        $date_records_model->rollback();
                        $code = 10024; //数据库错误
                        $msg = "用户".$friend_info['mobile'].$this->_error_msg->system_errors[$code];
                        return $this->echo_message($msg,$code);
                    }

                    $friendship = $user_list_model->getFriends($val, $uid); //查询我对该好朋友的备注
                    $notice_model->dateInvite($val, $friendship['remark']); //添加通知
                    #给被添加约会的人推送
                    if(!empty($friend_info['push_token']) && $uid != $friend_info['uid']){
                        $push_msg_model = new PushMsg();  //友盟
                        $push_msg_model->addPushOfDate($friendship['remark'] ,$friend_info['push_token']);
                    }
                }
            }else{
                $date_records_model->rollback();
                $code = 26003; //创建失败
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }
            $date_records_model->commit();

        }else{ //ID不为空，即修改约会信息
            $date_info = $date_records_model->getDataById($date_id); //查询约会信息
            if(empty($date_info)){
                $code = 26005; //约会不存在，请退出重试
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            if($date_info['uid'] != $uid ){
                $code = 26004; //您不是该约会的发起人，无权修改哦～
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            #修改约会信息
            $date_update = array(
                'destination' => $destination,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'updated_at' => $time,
                'begin_at' => $begin_at
            );
            $ret = $date_records_model->updateDataById($date_update, $date_id);

            if($ret) { //修改成功的话
                $result = $appointment_model->getDataByDateId($date_id);//查询参加约会的所有人

                $uids_info = array();
                if(!empty($result)){
                    foreach($result as $key => $val){
                        $uids_info[$val['uid']] = $val;
                        if(empty($uids[$val['uid']]) && $val['uid'] != $uid){ //不存在，说明该用户被移除了,创建者本人不可以删除
                            $appointment_model->deleteData($val['id']); //删除该用户
                        }
                    }
                }

                $uids[] = $uid;
                foreach ($uids as $val) {
                    if (!empty($uids_info[$val])) {//已经参与的人，修改位置信息
                        $update_appoint_info = array(
                            'destination' => $destination,
                            'longitude' => $longitude,
                            'latitude' => $latitude,
                            'updated_at' => $time,
                            'begin_at' => $begin_at
                        );
                        $appointment_model->updateDataById($update_appoint_info, $uids_info[$val]['id']);
                    } else { //新增的人
                        $friend_info = $user_model->getUserInfoByUid($val); //查询用户信息
                        if(empty($friend_info)){
//                            $code = 20049; //用户不存在或已注销
//                            $msg = $this->_error_msg->system_errors[$code];
//                            return $this->echo_message($msg,$code);
                            continue;
                        }

                        $on_date = $appointment_model->getDataByUid($val);//查询用户是否已经处于约会
                        if($on_date){
                            continue;
                        }

                        $appoint_info = array(
                            'date_id' => $date_id,
                            'uid' => $val,
                            'promoter' => $uid,
                            'destination' => $destination,
                            'longitude' => $longitude,
                            'latitude' => $latitude,
                            'expired_at' => $date_info['expired_at'],
                            'created_at' => $time,
                            'begin_at' => $begin_at
                        );
                        $appointment_model->addData($appoint_info);

                        $friendship = $user_list_model->getFriends($val, $uid); //查询我对该好朋友的备注
                        $notice_model->dateInvite($val, $friendship['remark']); //添加通知
                        #给被添加约会的人推送
                        if(!empty($friend_info['push_token']) && $friend_info['uid'] != $uid){
                            $push_msg_model = new PushMsg();  //友盟
                            $push_msg_model->addPushOfDate($friendship['remark'] ,$friend_info['push_token']);
                        }
                    }
                }
            }else{
                $code = 26003; //创建失败
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }
        }


        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }

    #解散约会信息
    function dealDateAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $date_id = isset($_REQUEST['date_id']) ? $_REQUEST['date_id'] : '0';  //约会ID
        if(empty($date_id)){
            $code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        $date_records_model =  new DateRecordsModel();
        $date_info = $date_records_model->getDataById($date_id); //查询约会信息
        if(empty($date_info)){
            $code = 26005; //约会不存在，请退出重试
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        if($date_info['uid'] != $uid ){
            $code = 26004; //您不是该约会的发起人，无权修改哦～
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        #修改约会信息已结束
        $update = array(
            'status' => 2 //约会状态，1-进行中， 2-已结束
        );
        $date_records_model->updateDataById($update, $date_id);

        #修改该约会的每一个人
        $appointment_model = new AppointmentModel();
        $appointment_model->updateDataByDateId($update, $date_id);

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }

    #查看我的约会信息,获取每个人此时的位置
    function getDateInfoAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $uids = $return = $infor_fri = array();

        $user_model = new UserModel();
        $appointment_model = new AppointmentModel();
        $info = $appointment_model->getDataByUid($uid); //我是否有约会
        if(empty($info)){ //我没有约会，显示空信息
            return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
        }
        $return['date_info']  = $info;

        $new_location_model = new NewLocationModel();
        $user_list_model = new UserListModel();
        $user_info = $user_model->getUserInfoByUid($uid);

        if($info['uid'] != $info['promoter']){ //我不是创建者的情况
            if(empty($user_info['member'])){ //我不是会员，只能看到创建者和自己的位置
                $uids = array($info['uid'], $info['promoter']);
                $return['date_info']['part_info'] = $new_location_model->getDataByUids($uids);
                if(!empty($return['date_info']['part_info'] )){
                    foreach($return['date_info']['part_info'] as $key => $val){

                        if($uid == $val['uid']){
                            $infor_fri['remark'] = "自己";
                            $infor_fri['avatar'] = $user_info['avatar'];
                        }else{
                            $infor_fri = $user_list_model->getFriends($uid, $val['uid']);
                        }
                        $return['date_info']['part_info'][$key]['friend_id'] =  $val['uid'];
                        unset($return['date_info']['part_info'][$key]['uid']);
                        $return['date_info']['part_info'][$key]['nickname'] = $infor_fri['remark'];
                        $return['date_info']['part_info'][$key]['avatar'] = !empty($infor_fri['avatar']) ? QINIU_DOMAIN . $infor_fri['avatar'] : '';
                    }
                }

                $return['more_info_note'] = 1;
                return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE,$return);
            }
        }

        #能看到所有人的位置信息
        $date_info = $appointment_model->getDataByDateId($info['date_id']);//根据约会ID查找，没有判断是否是约会进行中，因为约会大家要么都一起结束了，要么退出的话，信息就删除了
        foreach($date_info as $value){
            $uids[] = $value['uid'];
        }

        $return['date_info']['part_info'] = $new_location_model->getDataByUids($uids); //获取所有人的最新位置
        if(!empty($return['date_info']['part_info'] )){
            foreach($return['date_info']['part_info'] as $key => $val){
                if($uid == $val['uid']){
                    $infor_fri['remark'] = "自己";
                    $infor_fri['avatar'] = QINIU_DOMAIN . $user_info['avatar'];
                }else{
                    $infor_fri = $user_list_model->getFriends($uid, $val['uid']);
                }

                $user_info = $user_model->getUserInfoByUid($val['uid']);
                $return['date_info']['part_info'][$key]['friend_id'] =  $val['uid'];
                unset($return['date_info']['part_info'][$key]['uid']);
                $return['date_info']['part_info'][$key]['nickname'] = $infor_fri['remark'];
                $return['date_info']['part_info'][$key]['avatar'] = !empty($infor_fri['avatar']) ? QINIU_DOMAIN . $infor_fri['avatar'] : QINIU_DOMAIN . AVATAR;
            }
        }
        $return['more_info_note'] = 0;
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE,$return);

    }


    #作为非创建者,主动退出一个约会
    function quitDateAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口

        $appointment_model = new AppointmentModel();
        $info = $appointment_model->getDataByUid($uid); //我是否有约会
        if(empty($info)){ //我没有约会，显示空信息
            $code = 26005;// 约会不存在,请退出重试
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        if($info['uid'] == $info['promoter']){ //我是创建者的情况
            $code = 26008;// '您是发起人,不可以退出哦,试试取消约会吧～',
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        #退出约会
        $ret = $appointment_model->deleteData($info['id']);
        if(empty($ret)){
            $code = 10024;//数据库错误
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }

    #确认用户
    function checkAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $friend_id = isset($_REQUEST['friend_id']) ? intval($_REQUEST['friend_id']) : '0'; //参加的uid好友

        if(empty($friend_id)){
            $code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        $user_model = new UserModel();
        $friend_info = $user_model->getUserInfoByUid($friend_id); //查询用户信息
        if(empty($friend_info)){
            $code = 20049; //用户不存在或已注销
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        $appointment_model = new AppointmentModel();
        $on_date = $appointment_model->getDataByUid($friend_id);//查询用户是否已经处于约会
        if($on_date){
            $code = 26006; //'您已经处于一个约会中，请退出当前约会后再试'
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }

}